// vue实例对象
let $vue = null
function setVue (_vue) {
  $vue = _vue
}
function getVue () {
  return $vue
}

/**
 * 日期对象 赋予格式化函数挂载
 */
function dateFormatDefine () {
  window.Date.prototype.Format = function (fmt) {
    const cNumber = ['日', '一', '二', '三', '四', '五', '六']

    const o = {
      'M+': this.getMonth() + 1, // 月份
      'd+': this.getDate(), // 日
      'h+': this.getHours(), // 小时
      'm+': this.getMinutes(), // 分
      's+': this.getSeconds(), // 秒
      'w+': cNumber[this.getUTCDay()], // 星期
      'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
      S: this.getMilliseconds() // 毫秒
    }

    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        (this.getFullYear() + '').substr(4 - RegExp.$1.length)
      )
    }

    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }

    return fmt
  }
}
dateFormatDefine()


/**
 * 事件绑定移除 处理
 */
const eventHistory = {}
function kbindEvent (aim, eventName, callback) {
  const eventId = new Date().getTime()
  const fun = function () {
    callback()
  }

  eventHistory[eventId] = { fun: fun, aim: aim, eventName: eventName }

  aim.addEventListener(eventName, fun, false)

  return eventId
}

function kunbindEvent (eventid) {
  const eventData = eventHistory[eventid]

  eventData.aim.removeEventListener(eventData.eventName, eventData.fun, false)

  delete eventHistory[eventid]
}

/**
 * 解析url 为对象
 */
function kgetUrlinfo (hash) {
  const list = hash.split('#')

  const r = {}
  let arr = list[0].split('?')

  if (arr.length > 1) {
    arr = arr[1].split('&')
  } else {
    arr = []
  }

  for (let i = 0; i < arr.length; i++) {
    const s = arr[i].split('=')

    if (s.length > 0 && s[0] !== '') {
      if (s.length === 1) {
        s[1] = ''
      }

      r[s[0]] = decodeURIComponent(s[1])
    }
  }

  if (list.length > 1) {
    r.URLHASH = kgetUrlinfo(list[1])
  }

  return r
}

/* 传入对象，进行url拼接处理 */
function KhttpBuildQuery (list) {
  const str = '?'

  const params = []

  for (const i in list) {
    params.push(i + '=' + encodeURIComponent(list[i]))
  }

  return str + params.join('&')
}

/**
 * 加载引入js 文件
 */
const scriptHistory = {}
function loadScript (srcUrl) {
  return new Promise((resolve, reject) => {
    if (scriptHistory[srcUrl]) {
      resolve()
      return
    }

    const script = document.createElement('script')

    script.onload = () => {
      resolve()
    }

    script.onerror = () => {
      reject(new Error('script error'))
    }

    scriptHistory[srcUrl] = true
    script.src = srcUrl
    document.body.appendChild(script)
  })
}

/**
 * @param {Object} json
 * json 字符串转换 防止报错
 */
function kJsonParse (json) {
  try {
    return JSON.parse(json)
  } catch (e) {
    return false
  }
}

/**
 * 时间定时器 自动清理
 */
let IntervalList = {}
function setTimerInterval (id) {
  IntervalList[id] = true
}

/**
 * 自动清理函数
 */
function clearIntervalAutoPageChange () {
  for (const i in IntervalList) {
    clearInterval(i)
  }

  IntervalList = {}
}

export default {
  setVue: setVue,
  getVue: getVue,
  loadScript: loadScript,
  KhttpBuildQuery: KhttpBuildQuery,
  kgetUrlinfo: kgetUrlinfo,
  kbindEvent: kbindEvent,
  kunbindEvent: kunbindEvent,
  kJsonParse: kJsonParse,
  clearIntervalAutoPageChange: clearIntervalAutoPageChange,
  setTimerInterval: setTimerInterval
}
